//
// LastfmBackend.cs
//
// Copyright (C) 2008 Lukas Lipka <lukaslipka@gmail.com>
//

using System;
using System.Collections.Generic;

using Dashboard;
using Dashboard.Util;

using Lastfm;

namespace Dashboard.Engine.Backends {

	public class LastfmBackend : Backend, IComponent {

		private const int MAX_NUM_ARTISTS = 1;

		public void Initialize () 
		{
			//LastfmAlbumInfo album = Lastfm.Lastfm.GetAlbumInfo ("Metallica", "Metallica");
			//Console.WriteLine (album.ReleaseDate);
			//foreach (LastfmArtistTopTrack track in Lastfm.Lastfm.GetArtistTopTracks ("Metallica"))
			//	Console.WriteLine (track.Name);

			//Engine.MessageBroker.Subscribe ("/event/media/playing", typeof (ClueMessage), OnMessage);

			Register ("similiar-artist", SimiliarArtist);
		}

		public void Dispose ()
		{
			//Engine.MessageBroker.Unsubscribe (OnMessage);
		}

		private IEnumerable<Match> SimiliarArtist (ClueMessage clue_message)
		{
			foreach (Clue clue in clue_message.Clues) {
				if (clue.Type != "db:media")
					continue;
					
				string artist = clue.Properties.GetPropertyValue ("db:artist");

				if (String.IsNullOrEmpty (artist))
					continue;

				int count = 0;

				foreach (LastfmArtistSimilarArtist similar in Lastfm.Lastfm.GetArtistSimilarArtists (artist)) {
					if (count++ >= MAX_NUM_ARTISTS)
						break;

					Match match = new Match ();
					match.Trigger = clue_message.Id;
					match.Type = "db:lastfm"; // FIXME: This type sucks
					match.Uri = new Uri (similar.Url);
					match.Properties.Add (new Property ("dc:title", "dc:string", similar.Name));
					match.Properties.Add (new Property ("db:similarity", "dc:double", similar.Match.ToString ()));

					yield return match;
				}
			}
		}

		public string Name {
			get { return "Last.FM"; }
		}

		public string Description {
			get { return "Audioscrobbler's music recommendations, charts, concerts and taste-o-meters."; }
		}
	}
}
